<!DOCTYPE html>


<html lang="zh-Hans">


<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    入门经典第三章之字符串（上） |  Veal&#39;s Blog
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

<link rel="alternate" href="/atom.xml" title="Veal's Blog" type="application/atom+xml">
<link href="https://cdn.bootcss.com/KaTeX/0.11.1/katex.min.css" rel="stylesheet" /></head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-UVaOJ2"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  入门经典第三章之字符串（上）
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/07/30/UVaOJ2/" class="article-date">
  <time datetime="2020-07-30T09:27:52.000Z" itemprop="datePublished">2020-07-30</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E7%AE%97%E6%B3%95%E7%AB%9E%E8%B5%9B/">算法竞赛</a> / <a class="article-category-link" href="/categories/%E7%AE%97%E6%B3%95%E7%AB%9E%E8%B5%9B/cpp%E5%9F%BA%E7%A1%80/">cpp基础</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">2.8k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">11 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <p>第三章主要介绍数组和字符串在算法中的应用，原书基于C语言风格字符数组，介绍sprintf, strchr等string.h库中方法。在本篇博客中记录与之对应cpp对于vector, string的处理方法。</p>
<p>在知识构建方面，我倾向于按照以下思路逐步递进：</p>
<ul>
<li>1 数据结构的定义与初始化</li>
<li>2 定义在数据结构上的基本操作</li>
<li>3 遍历访问</li>
</ul>
<a id="more"></a>

<h2 id="字符串"><a href="#字符串" class="headerlink" title="字符串"></a>字符串</h2><h3 id="初始化-amp-赋值"><a href="#初始化-amp-赋值" class="headerlink" title="初始化 &amp; 赋值"></a>初始化 &amp; 赋值</h3><p>初始化可分为<strong>直接初始化</strong>与<strong>拷贝初始化</strong>。<br>赋值可用=或assign函数进行字符串赋值，其中assign返回值为字符串的引用。<br><em>初学者需要注意，初始化与赋值并不是同一个概念！</em></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;string&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>; <span class="comment">//必要头文件</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">//初始化</span></span><br><span class="line">    <span class="built_in">string</span> s1; <span class="comment">//默认初始化</span></span><br><span class="line">    <span class="function"><span class="built_in">string</span> <span class="title">s2</span><span class="params">(<span class="string">"value"</span>)</span></span>; <span class="comment">//直接初始化</span></span><br><span class="line">    <span class="function"><span class="built_in">string</span> <span class="title">s3</span><span class="params">(<span class="number">3</span>, <span class="string">'c'</span>)</span></span>; <span class="comment">// s3 = "ccc" 直接初始化</span></span><br><span class="line">    <span class="built_in">string</span> s4 = s2; <span class="comment">//拷贝初始化</span></span><br><span class="line">    <span class="comment">//赋值</span></span><br><span class="line">    <span class="built_in">string</span> s5;</span><br><span class="line">    s5 = s4; <span class="comment">//将s4赋值给s5</span></span><br><span class="line">    s5.assign(<span class="string">"12345"</span>); <span class="comment">// s5 = 12345 assgin返回s5的引用</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="string对象上的操作"><a href="#string对象上的操作" class="headerlink" title="string对象上的操作"></a>string对象上的操作</h3><h4 id="empty和size"><a href="#empty和size" class="headerlink" title="empty和size"></a>empty和size</h4><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">s.empty() <span class="comment">// s为空返回true，否则返回false</span></span><br><span class="line">s.size() <span class="comment">// 返回s中字符的个数</span></span><br></pre></td></tr></table></figure>

<h5 id="string-size-type类型"><a href="#string-size-type类型" class="headerlink" title="string::size_type类型"></a>string::size_type类型</h5><p>显然，size函数的返回值为int或unsigned int，但其实size函数返回的是一个string::size_type类型的值，此处我们并不需要了解这个类型的细节，但需要明确的是，它是一个unsigned int的值而且足以存放任何string对象的大小。<br><strong>尤为注意的是</strong>，如果在表达式中混用了带符号和无符号数，可能会出现意想不到的结果：例如，假如int n=-1, 则表达式 s.size() &lt; n 为真，<strong>因为负值n会自动地转化为一个比较大的无符号值</strong>。</p>
<p>示例代码</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;string&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="function"><span class="built_in">string</span> <span class="title">s1</span><span class="params">(<span class="string">"hello"</span>)</span></span>;</span><br><span class="line">    <span class="keyword">int</span> n = <span class="number">-1</span>;</span><br><span class="line">    <span class="comment">// size与empty操作</span></span><br><span class="line">    <span class="keyword">if</span> (s1.size() &lt; n)</span><br><span class="line">        <span class="built_in">cout</span> &lt;&lt; <span class="string">"wrong answer!"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    <span class="comment">// more info</span></span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="string">"s1 is empty? "</span> &lt;&lt; s1.empty() &lt;&lt; <span class="built_in">endl</span>; </span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="string">"length of s1 is"</span> &lt;&lt; s1.size() &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="字符串比较与拼接"><a href="#字符串比较与拼接" class="headerlink" title="字符串比较与拼接"></a>字符串比较与拼接</h5><h6 id="比较规则"><a href="#比较规则" class="headerlink" title="比较规则"></a>比较规则</h6><p>依<strong>大小写敏感字典序</strong>(A-Za-z升序)进行比较：<br>1.如果两个string对象的长度不同，而且较短string对象的每个字符都与较长string对象对应位置上的字符相同，就说较短string对象小于较长string对象。<br>2.如果两个string对象在某些对应的位置上不一致，则string对象比较的结果其实是string对象中第一对相异字符比较的结果。</p>
<p><strong>比较运算符</strong></p>
<p>&lt;、&lt;=、==、!=、&gt;=、&gt;</p>
<p><em>string对象比较的示例:</em></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">string</span> s1 = <span class="string">"abby"</span>;</span><br><span class="line"><span class="built_in">string</span> s2 = <span class="string">"abby finder"</span>;</span><br><span class="line"><span class="built_in">string</span> s3 = <span class="string">"abbY"</span>;</span><br><span class="line"><span class="built_in">string</span> s4 = <span class="string">"Zbby"</span>;</span><br></pre></td></tr></table></figure>

<p>则有<br>s1 &lt; s2, s1 &gt; s3, s1 &gt; s4</p>
<h5 id="字符串拼接"><a href="#字符串拼接" class="headerlink" title="字符串拼接"></a>字符串拼接</h5><h6 id="运算符"><a href="#运算符" class="headerlink" title="运算符"></a>运算符</h6><p>对string对象使用加法运算符（+）：<br>一个新的string对象，它所包含的字符由两部分组成：前半部分是加号左侧string对象所含的字符、后半部分是加号右侧string对象所含的字符。<br>复合赋值运算符（+=）：<br>负责把右侧string对象的内容追加到左侧string对象的后面。</p>
<h6 id="append方法"><a href="#append方法" class="headerlink" title="append方法"></a>append方法</h6><p>可直接向原有字符串追加新内容</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">string</span> s1 = <span class="string">"Hello"</span>;</span><br><span class="line"><span class="built_in">string</span> s2 = <span class="string">"World"</span>;</span><br><span class="line">s1.append(s2); <span class="comment">// s1 = "HelloWorld"</span></span><br><span class="line"><span class="built_in">string</span> s3 = <span class="string">"Hi"</span>;</span><br><span class="line">s3 += s2; <span class="comment">// s3 = "HiWorld" </span></span><br><span class="line"><span class="built_in">string</span> s4;</span><br><span class="line">s4 = <span class="string">"Good"</span> + s2; <span class="comment">// s4 = "GoodWorld"</span></span><br></pre></td></tr></table></figure>

<h4 id="子串相关操作"><a href="#子串相关操作" class="headerlink" title="子串相关操作"></a>子串相关操作</h4><h5 id="求子串"><a href="#求子串" class="headerlink" title="求子串"></a>求子串</h5><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="built_in">string</span> <span class="title">substr</span><span class="params">(<span class="keyword">int</span> n = <span class="number">0</span>, <span class="keyword">int</span> m = <span class="built_in">string</span>::npos)</span> <span class="keyword">const</span></span>;</span><br></pre></td></tr></table></figure>
<p>返回原字符串从下标n开始，长度为m的子串，如果省略m，则到字符串结束</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">string</span> s1 = <span class="string">"this is ok"</span>;</span><br><span class="line"><span class="built_in">string</span> s2 = s1.substr(<span class="number">2</span>, <span class="number">4</span>);  <span class="comment">// s2 = "is i"</span></span><br><span class="line">s2 = s1.substr(<span class="number">2</span>);  <span class="comment">// s2 = "is is ok"</span></span><br></pre></td></tr></table></figure>

<h5 id="查找子串"><a href="#查找子串" class="headerlink" title="查找子串"></a>查找子串</h5><p>string 类有一些查找子串和字符的成员函数，它们的返回值都是子串或字符在 string 对象字符串中的位置（即下标）。<strong>如果查不到，则返回 string::npos。</strong></p>
<p>函数原型</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">size_t</span> <span class="title">find</span> <span class="params">(<span class="keyword">const</span> <span class="built_in">string</span>&amp; str, <span class="keyword">size_t</span> pos = <span class="number">0</span>)</span> <span class="keyword">const</span> <span class="keyword">noexcept</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">size_t</span> <span class="title">rfind</span> <span class="params">(<span class="keyword">const</span> <span class="built_in">string</span>&amp; str, <span class="keyword">size_t</span> pos = npos)</span> <span class="keyword">const</span> <span class="keyword">noexcept</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">size_t</span> <span class="title">find_first_of</span> <span class="params">(<span class="keyword">const</span> <span class="built_in">string</span>&amp; str, <span class="keyword">size_t</span> pos = <span class="number">0</span>)</span> <span class="keyword">const</span> <span class="keyword">noexcept</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">size_t</span> <span class="title">find_last_of</span> <span class="params">(<span class="keyword">const</span> <span class="built_in">string</span>&amp; str, <span class="keyword">size_t</span> pos = npos)</span> <span class="keyword">const</span> <span class="keyword">noexcept</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">size_t</span> <span class="title">find_first_not_of</span> <span class="params">(<span class="keyword">const</span> <span class="built_in">string</span>&amp; str, <span class="keyword">size_t</span> pos = <span class="number">0</span>)</span> <span class="keyword">const</span> <span class="keyword">noexcept</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">size_t</span> <span class="title">find_last_not_of</span> <span class="params">(<span class="keyword">const</span> <span class="built_in">string</span>&amp; str, <span class="keyword">size_t</span> pos = npos)</span> <span class="keyword">const</span> <span class="keyword">noexcept</span></span>;</span><br></pre></td></tr></table></figure>

<p>s.find(s2)：<br>find s2 as a substring of s in s1, return the first index of s2 in s1.(find in increasing order)<br>从前往后查找子串或字符出现的位置。<br>s.rfind(s2):<br>find s2 as a substring of s in s1, return the first index of s2 in s1.(find in descending order, result same as find method)<br>从后往前查找子串或字符出现的位置。<br><em>find与rfind返回的结果相同，区别只是在给定特定条件下，顺序查找与逆序查找效率不同</em></p>
<p>s.find_first_of(s2):<br>for char u $\in$ s, if u $\in$ s2, return the first u’s index. (find in increasing order)<br>从前往后查找何处出现另一个字符串中包含的<em>任一<em>字符。<br>s.find_last_of(s2):<br>for char u $\in$ s, if u $\in$ s2, return the first u’s index. (find in descending order)<br>从后往前查找何处出现另一个字符串中包含的</em>任一*字符。<br>*find_first_of与find_last_of返回的结果不同，如果无法查到字符串中的任一字符，则返回string::npos</em></p>
<p>s.find_first_not_of(s2):<br>for char u $\in$ s, if u $\notin$ s2, return the first u’s index. (find in increasing order)<br>从前往后查找何处出现另一个字符串中没有包含的字符<br>s.find_last_not_of(s2):<br>for char u $\in$ s, if u $\notin$ s2, return the first u’s index. (find in descending order)<br>从后往前查找何处出现另一个字符串中没有包含的字符</p>
<h5 id="替换子串"><a href="#替换子串" class="headerlink" title="替换子串"></a>替换子串</h5><p>函数原型</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="built_in">string</span>&amp; <span class="title">replace</span> <span class="params">(<span class="keyword">size_t</span> pos, <span class="keyword">size_t</span> len, <span class="keyword">const</span> <span class="built_in">string</span>&amp; str, <span class="keyword">size_t</span> subpos, <span class="keyword">size_t</span> sublen = npos)</span></span>;</span><br></pre></td></tr></table></figure>

<p>s.replace(i, k, s2, j, m)<br>将s的子串s(i,k)(下标从i开始，长度为k的s子串)替换为s2的子串s2(j, m)(下标从j开始，长度为m的s2子串)。</p>
<h5 id="插入子串"><a href="#插入子串" class="headerlink" title="插入子串"></a>插入子串</h5><p>函数原型</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="built_in">string</span>&amp; <span class="title">insert</span> <span class="params">(<span class="keyword">size_t</span> pos, <span class="keyword">const</span> <span class="built_in">string</span>&amp; str, <span class="keyword">size_t</span> subpos, <span class="keyword">size_t</span> sublen)</span></span>;</span><br></pre></td></tr></table></figure>

<p>s.insert(i, s2, j, m)<br>字符串s从下标i开始插入子串s2(j,m)(s2下标从j开始，长度为m的子串)</p>
<h5 id="删除子串"><a href="#删除子串" class="headerlink" title="删除子串"></a>删除子串</h5><p>函数原型</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="built_in">string</span>&amp; <span class="title">erase</span> <span class="params">(<span class="keyword">size_t</span> pos = <span class="number">0</span>, <span class="keyword">size_t</span> len = npos)</span></span>;</span><br></pre></td></tr></table></figure>

<p>s.erase(i, k)<br>从字符串s中删除s的子串s(i,k)(下标为i, 长度为k的子串)</p>
<h4 id="读写及其他操作"><a href="#读写及其他操作" class="headerlink" title="读写及其他操作"></a>读写及其他操作</h4><h5 id="将string对象作为流处理"><a href="#将string对象作为流处理" class="headerlink" title="将string对象作为流处理"></a>将string对象作为流处理</h5><p>使用流对象 istringstream 和 ostringstream，可以将 string 对象当作一个流进行输入输出。使用这两个类需要包含头文件 sstream。这可与c语言中的sscanf, sprintf对标。</p>
<p>使用IO读入string，string会自动忽略开头的空白（空格符、换行符及制表符等），读取字符串，直到遇到下一个空格(也即字符串以空格进行分割)。</p>
<p>示例代码</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sstream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;string&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="function"><span class="built_in">string</span> <span class="title">src</span><span class="params">(<span class="string">"Avatar 123 5.2 Titanic K"</span>)</span></span>;</span><br><span class="line">    <span class="function"><span class="built_in">istringstream</span> <span class="title">istrStream</span><span class="params">(src)</span></span>; <span class="comment">//建立src到istrStream的联系</span></span><br><span class="line">    <span class="built_in">string</span> s1, s2;</span><br><span class="line">    <span class="keyword">int</span> n;  <span class="keyword">double</span> d;  <span class="keyword">char</span> c;</span><br><span class="line">    istrStream &gt;&gt; s1 &gt;&gt; n &gt;&gt; d &gt;&gt; s2 &gt;&gt; c; <span class="comment">//把src的内容当做输入流进行读取</span></span><br><span class="line">    <span class="built_in">ostringstream</span> ostrStream;</span><br><span class="line">    ostrStream &lt;&lt; s1 &lt;&lt; <span class="built_in">endl</span> &lt;&lt; s2 &lt;&lt; <span class="built_in">endl</span> &lt;&lt; n &lt;&lt; <span class="built_in">endl</span> &lt;&lt; d &lt;&lt; <span class="built_in">endl</span> &lt;&lt; c &lt;&lt;<span class="built_in">endl</span>;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; ostrStream.str();</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出<br>Avatar<br>Titanic<br>123<br>5.2<br>K</p>
<h5 id="getline方法-保留空格"><a href="#getline方法-保留空格" class="headerlink" title="getline方法(保留空格)"></a>getline方法(保留空格)</h5><p>函数原型</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">istream&amp; <span class="title">getline</span> <span class="params">(istream&amp;  is, <span class="built_in">string</span>&amp; str)</span></span>;</span><br></pre></td></tr></table></figure>

<p>有时，我们希望能够保留字符串中的空格，这时需要使用getline方法。getline函数的参数是一个输入流和一个string对象，返回值为流参数。</p>
<p>函数从给定的输入流中读入内容，直到遇到换行符为止（注意换行符也被读进来了），然后把所读的内容存入到那个string对象中去（注意不存换行符）。getline只要一遇到换行符就结束读取操作并返回结果，哪怕输入的一开始就是换行符也是如此。如果输入真的一开始就是换行符，那么所得的结果是个空string。</p>
<h3 id="遍历访问"><a href="#遍历访问" class="headerlink" title="遍历访问"></a>遍历访问</h3><p>我们经常需要单独处理string对象中的字符，比如检查一个string对象是否包含空白，或者把string对象中的字母改成小写，再或者查看某个特定的字符是否出现等。</p>
<p>因此，这将涉及到两个关键问题：</p>
<ul>
<li>1 获取字符串中的每个字符</li>
<li>2 判定字符的特性</li>
</ul>
<p>对于第二个问题，cctype头文件中定义一系列函数帮助我们判定字符特性，如是否为数字，是否大写或小写</p>
<div aglin="center"><img src="/images/UVAOJ2/cctype.png"></div>

<p>对于第一个问题，我将从以下三方面进行讨论：</p>
<ul>
<li>1 全序列遍历</li>
<li>2 遍历全序列并修改字符</li>
<li>3 随机访问</li>
</ul>
<h4 id="全序列遍历"><a href="#全序列遍历" class="headerlink" title="全序列遍历"></a>全序列遍历</h4><p>使用C++11新标准提供的一种语句：范围for（range for）语句。这种语句<strong>遍历给定序列中的每个元素</strong>并<strong>对序列中的每个值执行某种操作</strong>，其语法形式是：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(declaration: expression)</span><br><span class="line">    statement</span><br></pre></td></tr></table></figure>

<p>其中，expression 部分是一个对象，用于表示一个序列。declaration 部分负责定义一个变量，该变量将被用于访问序列中的基础元素。<strong>每次迭代</strong>，declaration部分的变量会<strong>被初始化为expression部分的下一个元素值</strong>。</p>
<p>示例</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="built_in">string</span> <span class="title">s</span><span class="params">(<span class="string">"HelloWorld"</span>)</span></span>;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">auto</span> c : s)</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; c &lt;&lt; <span class="built_in">endl</span>;</span><br></pre></td></tr></table></figure>

<p>此例中，通过使用auto关键字让编译器来决定变量c的类型，这里c的类型是char。每次迭代，str的下一个字符被拷贝给c。</p>
<h4 id="遍历全序列并修改字符"><a href="#遍历全序列并修改字符" class="headerlink" title="遍历全序列并修改字符"></a>遍历全序列并修改字符</h4><p>如果想要改变string对象中字符的值，必须把循环变量定义成引用类型。当使用引用作为循环控制变量时，这个变量实际上<strong>被依次绑定到了序列的每个元素</strong>上。使用这个引用，我们就能改变它绑定的字符。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="built_in">string</span> <span class="title">s</span><span class="params">(<span class="string">"HelloWorld"</span>)</span></span>;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">auto</span> &amp;c : s)</span><br><span class="line">    c = <span class="built_in">toupper</span>(c);</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; s &lt;&lt; <span class="built_in">endl</span>;</span><br></pre></td></tr></table></figure>

<h4 id="随机访问"><a href="#随机访问" class="headerlink" title="随机访问"></a>随机访问</h4><p>要想访问string对象中的单个字符有两种方式：一种是使用下标，另外一种是使用迭代器。这里我仅介绍通过下标访问字符串</p>
<p>下标运算符（[]）接收的输入参数是string:：size type类型的值，这个参数表示要访问的字符的位置；返回值是该位置上字符的引用。<br>string对象的下标从0计起。如果string对象s至少包含两个字符，则s[0]是第1个字符、s[1]是第2个字符、s[s.size()-1]是最后一个字符。</p>
<p><em>只要字符串不是常量，就能为下标运算符返回的字符赋新值。</em></p>
<h5 id="越界检查"><a href="#越界检查" class="headerlink" title="越界检查"></a>越界检查</h5><p>使用下标进行随机访问，需要对下标进行检查，使其限制在0~size()-1 的范围内，标准库不会检查下标是否合法，因此一旦下标超出范围，可能会出现不可预知的结果！</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (!s.empty())</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; s[<span class="number">0</span>] &lt;&lt; <span class="built_in">endl</span>; <span class="comment">//使用下标需要判断字符串是否为空</span></span><br></pre></td></tr></table></figure>

<p>关于字符串基础知识就介绍到这里啦！在入门经典第三章之字符串（下），我会以UVAOJ中的字符串题目为例，具体应用字符串及定义在其上的运算~</p>
<p>关于基础字符串的示例代码，可以进入我的github<a href="https://github.com/VealM/UVaOJ" target="_blank" rel="noopener">仓库</a>查看~<br>参考链接：</p>
<p><a href="http://www.cplusplus.com/reference/string/string/insert/?kw=string%3A%3Ainsert" target="_blank" rel="noopener">官方文档 cpluscplus</a><br><a href="https://www.amazon.com/Primer-5th-Stanley-B-Lippman/dp/0321714113" target="_blank" rel="noopener">c++primer第五版</a><br><a href="https://blog.csdn.net/longzaitianya1989/article/details/52909786" target="_blank" rel="noopener">c语言中文网</a></p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>Copyright： </strong>
          Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://vealm.gitee.io/2020/07/30/UVaOJ2/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/cpp%E5%AD%97%E7%AC%A6%E4%B8%B2/" rel="tag">cpp字符串</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/08/06/UVaOJ3/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            入门经典第三章之字符串（下）
          
        </div>
      </a>
    
    
      <a href="/2020/07/27/UVAOJ1/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">入门经典第一、二章</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "854ziDXtPQxK8dJf2vsosmzN-gzGzoHsz",
    app_key: "kV9lcyv3dVA2I6pqA4yd23p6",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2020
        <i class="ri-heart-fill heart_icon"></i> Veal
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        Powered by <a href="https://hexo.io" target="_blank">Hexo</a>
        <span class="division">|</span>
        Theme - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>Visitors:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>Views:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278599897&amp;web_id=1278599897'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Veal&#39;s Blog"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/Me">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    
    <!--加入音乐播放器-->

    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
  });

  MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for(i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.6/unpacked/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
  var ayerConfig = {
    mathjax: true
  }
</script>

<!-- Katex -->


    
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css">
        <script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/auto-render.min.js"></script>
        
    


<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>